import cv2 as cv
import numpy as np
import copy

filename = r'pic.png'

img = cv.imread(filename)

#cv.imshow('original img',img)
gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)

otsuthd,bw = cv.threshold(gray,0,255,cv.THRESH_OTSU)
element = cv.getStructuringElement(cv.MORPH_CROSS,(3,3))
bw = cv.morphologyEx(bw,cv.MORPH_OPEN,element)

seg = copy.deepcopy(bw)

cnts,hier = cv.findContours(seg,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)

count = 0
arealist = []
arclengthlist = []

for i in range(len(cnts),0,-1):
    c = cnts[i-1]
    area = cv.contourArea(c)
    arclength = cv.arcLength(c,True)
    print("area：",area)
    print("arclength：",arclength)
    arealist.append(area)
    arclengthlist.append(arclength)
    if area<10:
        continue
    count += 1

    x,y,w,h = cv.boundingRect(c)
    cv.rectangle(img,(x,y),(x+w,y+h),(0,0,0xff),1)
    cv.putText(img,str(count),(x,y),cv.FONT_HERSHEY_PLAIN,0.5,(0,0xff,0))

print("米粒数量：",count)
cv.imshow("源图",img)
cv.imshow("阈值化图",bw)

#求均值
area_mean = np.mean(arealist)
#求方差
area_var = np.var(arealist)
#求标准差
area_std = np.std(arealist,ddof=1)
print("area平均值为：%f" % area_mean)
print("area方差为：%f" % area_var)
print("area标准差为:%f" % area_std)

#求均值
arclength_mean = np.mean(arclengthlist)
#求方差
arclength_var = np.var(arclengthlist)
#求标准差
arclength_std = np.std(arclengthlist,ddof=1)
print("arclength平均值为：%f" % arclength_mean)
print("arclength方差为：%f" % arclength_var)
print("arclength标准差为:%f" % arclength_std)

#print(arealist)
num = 0
for item in arealist:
    big = area_mean + 3*area_std
    small = area_mean - 3*area_std
    if(item>=small and item<=big):
        num += 1
print("面积落在3sigma内的米粒数量为:%d" % num)

num = 0
for item in arclengthlist:
    big = arclength_mean + 3*arclength_std
    small = arclength_mean - 3*arclength_std
    if(item>=small and item<=big):
        num += 1
print("面积落在3sigma内的米粒数量为:%d" % num)

cv.waitKey()
cv.destroyAllWindows()